<template>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model="loading"
      :finished="finished"
      :finished-text="$t('没有更多了')"
      @load="onLoad"
    >
      <div v-for="(item, index) in list" :key="index">
        <slot :item="item" :index="index"></slot>
      </div>
      <van-empty
        v-if="list.length === 0 && !loading"
        :description="$t('暂无数据')"
      />
    </van-list>
  </van-pull-refresh>
</template>
<script>
import { Toast } from 'vant'

export default {
  name: 'PullRefreshList',
  props: {
    // 数据请求函数
    fetchData: {
      type: Function,
      required: true,
    },
    // 每页条数
    pageSize: {
      type: Number,
      default: 10,
    },
    // 初始参数
    initialParams: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      // 列表数据
      list: [],
      // 当前页码
      currentPage: 1,
      // 加载状态
      loading: false,
      // 下拉刷新状态
      refreshing: false,
      // 是否加载完成
      finished: false,
      // 请求参数
      params: {},
    }
  },
  created() {
    // 初始化参数
    this.params = { ...this.initialParams, nowPage: 1, pageSize: this.pageSize }
    console.log('[ this.initialParams ]-61', this.params)
  },
  methods: {
    // 下拉刷新
    onRefresh() {
      // 重置列表数据
      this.list = []
      this.currentPage = 1
      this.finished = false
      // 重新获取数据
      this.loadData().then(() => {
        this.refreshing = false
      })
    },

    // 上拉加载
    onLoad() {
      if (this.finished) return
      this.loadData().then(() => {
        this.loading = false
      })
    },

    // 加载数据
    async loadData() {
      try {
        this.params.nowPage = this.currentPage
        const response = await this.fetchData(this.params)
        const { rootArray, totalPage } = response.data

        if (this.currentPage === 1) {
          this.list = rootArray || []
        } else {
          this.list = [...this.list, ...(rootArray || [])]
        }

        // 判断是否加载完成
        if (this.currentPage >= totalPage) {
          this.finished = true
        } else {
          this.currentPage++
        }
        return Promise.resolve()
      } catch (error) {
        Toast(this.$t('数据加载失败'))
        return Promise.reject(error)
      }
    },

    // 手动刷新列表
    refreshList() {
      this.onRefresh()
    },

    // 更新请求参数并刷新
    updateParams(newParams) {
      this.params = { ...this.params, ...newParams, nowPage: 1 }
      this.onRefresh()
    },
  },
}
</script>
<style scoped>
/* 可以根据需要添加组件样式 */
</style>
